// 认证模块 - 用于 login.html
const AuthModule = {
    // 检查Token并自动登录
    checkTokenAndRedirect: async function() {
        const token = localStorage.getItem('token');
        if (!token) {
            return; // 没有token，停留在登录页
        }
        
        try {
            // 优先使用缓存的用户信息
            const cachedUser = localStorage.getItem('current_user');
            if (cachedUser) {
                // 有缓存，尝试静默验证token有效性
                try {
                    await Api.getCurrentUser(false); // 使用缓存，不强制刷新
                    // Token有效，直接跳转
                    window.location.href = 'index.html';
                    return;
                } catch (error) {
                    // Token可能过期，清除缓存后重试
                    console.log('缓存的token可能已过期，尝试重新验证...');
                }
            }
            
            // 没有缓存或token过期，重新请求用户信息
            await Api.getCurrentUser(true); // 强制刷新
            window.location.href = 'index.html';
            
        } catch (error) {
            // Token无效或过期，静默清除（不提示）
            Api.clearUserCache();
            localStorage.removeItem('token');
            console.log('Token验证失败，请重新登录');
        }
    },

    // 处理登录
    handleLogin: async function(fields) {
        const loginData = {
            username: fields.username,
            password: fields.password,
            mfa_token: fields.mfa_token || null
        };

        try {
            const data = await Api.apiRequest('/auth/login', {
                method: 'POST',
                body: JSON.stringify(loginData)
            });

            // 先清除所有旧数据
            Api.clearUserCache();
            localStorage.clear(); // 清除所有localStorage数据
            
            // 保存新token
            localStorage.setItem('token', data.access_token);
            
            // 登录成功后立即获取并缓存用户信息
            try {
                await Api.getCurrentUser(true); // 强制刷新用户信息
            } catch (error) {
                console.error('获取用户信息失败:', error);
            }
            
            console.log('登录成功，新token已保存');
            window.location.href = 'index.html';
            
        } catch (error) {
            if (window.layui && layui.layer) {
                layui.layer.msg(error.message || error.detail, { icon: 2 });
            } else {
                alert(error.message || error.detail);
            }
        }
    },

    // 提示输入MFA
    promptForMfa: function(fields) {
        layui.layer.prompt({
            formType: 0,
            title: '请输入MFA令牌',
            area: ['300px', '150px']
        }, (value, index, elem) => {
            layui.layer.close(index);
            fields.mfa_token = value;
            this.handleLogin(fields);
        });
    },

    // 处理注册
    handleRegister: async function(fields) {
        const userData = {
            username: fields.username,
            password: fields.password
        };

        if (userData.password !== fields.confirm_password) {
            layui.layer.msg('两次输入的密码不一致', { icon: 2 });
            return;
        }

        try {
            await Api.apiRequest('/auth/register', {
                method: 'POST',
                body: JSON.stringify(userData)
            });

            layui.layer.msg('注册成功，请登录', { icon: 1, time: 2000 }, function() {
                window.location.href = 'login.html';
            });
            
        } catch (error) {
            layui.layer.msg(error.message || error.detail, { icon: 2, time: 3000 });
        }
    },

    // WebAuthn密钥登录（无用户名驻留凭证登录）
    handleWebAuthnLogin: async function() {
        // 检查浏览器是否支持WebAuthn
        if (!window.PublicKeyCredential) {
            layui.layer.msg('您的浏览器不支持硬件密钥登录', { icon: 2 });
            return;
        }

        // 提示用户
        layui.layer.msg('请插入并触摸您的硬件密钥进行登录...', { icon: 16, time: 0, shade: 0.3 });

        try {
            // 1. 开始WebAuthn登录流程（不发送username）
            const beginData = await Api.apiRequest('/webauthn/login/begin', {
                method: 'POST',
                body: JSON.stringify({})  // 空对象，不包含username
            });

            layui.layer.closeAll('dialog');

            const options = beginData.options;

            // 2. 转换Base64字符串为ArrayBuffer
            options.challenge = this.base64urlToBuffer(options.challenge);
            if (options.allowCredentials && options.allowCredentials.length > 0) {
                options.allowCredentials = options.allowCredentials.map(cred => ({
                    ...cred,
                    id: this.base64urlToBuffer(cred.id)
                }));
            }

            // 3. 调用浏览器WebAuthn API
            const credential = await navigator.credentials.get({
                publicKey: options
            });

            // 4. 转换凭证响应为可传输格式
            const credentialForServer = {
                id: credential.id,
                rawId: this.bufferToBase64url(credential.rawId),
                type: credential.type,
                response: {
                    authenticatorData: this.bufferToBase64url(credential.response.authenticatorData),
                    clientDataJSON: this.bufferToBase64url(credential.response.clientDataJSON),
                    signature: this.bufferToBase64url(credential.response.signature),
                    userHandle: credential.response.userHandle ? this.bufferToBase64url(credential.response.userHandle) : null
                }
            };

            // 5. 完成登录
            const loadingIndex2 = layui.layer.load(1, { shade: [0.3, '#fff'] });
            // 不发送username，让后端通过凭证ID自动识别用户
            const loginData = await Api.apiRequest('/webauthn/login/complete', {
                method: 'POST',
                body: JSON.stringify({
                    credential: credentialForServer
                })
            });
            layui.layer.close(loadingIndex2);

            // 先清除所有旧数据
            Api.clearUserCache();
            localStorage.clear();
            
            // 保存新token
            localStorage.setItem('token', loginData.access_token);
            
            // 获取并缓存用户信息
            try {
                await Api.getCurrentUser(true);
            } catch (error) {
                console.error('获取用户信息失败:', error);
            }
            
            layui.layer.msg('密钥登录成功', { icon: 1 });
            setTimeout(() => {
                window.location.href = 'index.html';
            }, 500);

        } catch (error) {
            layui.layer.closeAll('dialog');
            console.error('WebAuthn登录失败:', error);
            
            let errorMsg = '密钥登录失败';
            if (error.name === 'NotAllowedError') {
                errorMsg = '您取消了密钥验证';
            } else if (error.message) {
                errorMsg = error.message;
            } else if (error.detail) {
                errorMsg = error.detail;
            }
            
            layui.layer.msg(errorMsg, { icon: 2, time: 3000 });
        }
    },

    // Base64URL转ArrayBuffer
    base64urlToBuffer: function(base64url) {
        const base64 = base64url.replace(/-/g, '+').replace(/_/g, '/');
        const padLen = (4 - (base64.length % 4)) % 4;
        const padded = base64 + '='.repeat(padLen);
        const binary = atob(padded);
        const buffer = new Uint8Array(binary.length);
        for (let i = 0; i < binary.length; i++) {
            buffer[i] = binary.charCodeAt(i);
        }
        return buffer.buffer;
    },

    // ArrayBuffer转Base64URL
    bufferToBase64url: function(buffer) {
        const bytes = new Uint8Array(buffer);
        let binary = '';
        for (let i = 0; i < bytes.length; i++) {
            binary += String.fromCharCode(bytes[i]);
        }
        return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, '');
    }
};

// 绑定密钥登录按钮事件
document.addEventListener('DOMContentLoaded', function() {
    const webauthnBtn = document.getElementById('webauthn-login-btn');
    if (webauthnBtn) {
        webauthnBtn.addEventListener('click', function(e) {
            e.preventDefault();
            AuthModule.handleWebAuthnLogin();
        });
    }
});
